var express = require('express');
var router = express.Router();
var config = require('../config/db')
var MongoClient = require('mongodb').MongoClient
var passport=require('passport')

/* 获取（查询）评论信息 */
router.get('/getCommentsByBookId', function (req, res, next) {
    //1.接受请求的用户编号参数
    // res.send('查询评论信息');
    var bookId = req.query.bookId
    //2.连接数据库
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            var db = client.db()
            db.collection('comments').aggregate([
                {
                    $lookup: {
                        from: 'user',
                        localField: 'user_id',
                        foreignField: 'user_id',
                        as: 'user'
                    }
                },
                {
                    $lookup: {
                        from: 'books',
                        localField: 'books_id',
                        foreignField: 'books_id',
                        as: 'books'
                    }
                },
                {
                    $match: {
                        // books_id: bookId
                        books_id: '1'
                    }
                },
                { $unwind: '$user' },
                { $unwind: '$books' }
            ]

            ).toArray(function (err, result) {
                if (err) {
                    console.log('err', err)
                } else {
                    console.log('res :', result)
                    res.json({ code: 200, message: 'ok', data: result })
                    client.close()
                }
            })
        }
    })
});

/* 添加评论 */
router.get('/addComments', function (req, res, next) {
    res.send('添加评论 ');
});

/* 删除评论 */
router.get('/delComments', function (req, res, next) {
    //1.接受删除评论需要使用的参数req.body
    var deleteComment = req.body
    //2.连接数据库MongoDB
    MongoClient.connect(config.url, function (err, client) {
        if (err) {
            console.log('数据库连接失败！', err)
            res.json({ code: 200, message: 'error', data: err })
        } else {
            //3.执行删除评论操作 db.deleteOne
            var db = client.db()
            db.collection('comments').deleteOne({ comments_id: deleteComment.commentId}, function (err, result) {
                if (err) {
                    console.log('删除数据失败！', err)
                } else {
                    //4.返回结果{code:0;message:'ok',data:{}}
                    res.json({ code: 200, message: 'ok', data: result })
                    client.close()
                }
            })
        }
    })
});

// /* 修改评论 */
// router.get('/updComments', function (req, res, next) {
//     res.send('修改评论');
// });

module.exports = router;